
var config = require('../config/config')
var crypto = require('crypto');  
var log4 = require('../tools/logs')

function raw(args) { 
    var keys = Object.keys(args); 
    keys = keys.sort() 
    var newArgs = {}; 
    keys.forEach(function(key) { 
      newArgs[key] = args[key]; 
    }); 
    var string = ''; 
    for (var k in newArgs) { 
      string += '&' + k + '=' + newArgs[k]; 
    } 
    string = string.substr(1); 
    return string; 
  }

exports.createNonceStr =  function () {  
    return Math.random().toString(36).substr(2, 15);  
};  

exports.createTimeStamp =  function() {
    var timestamp1 = Date.parse( new Date());
    return timestamp1;
}

exports.paysignjsapi =  function (appid, attach, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type) {  
    var ret = {  
        appid: appid,  
        attach: attach,  
        body: body,  
        mch_id: mch_id,  
        nonce_str: nonce_str,  
        notify_url: notify_url,  
        openid: openid,  
        out_trade_no: out_trade_no,  
        spbill_create_ip: spbill_create_ip,  
        total_fee: total_fee,  
        trade_type: trade_type  
    };  
    log4.logs('打印生成签名方法入参')
    log4.logs(ret)
    var string = raw(ret); 
    var key = config.key 
    string = string + '&key=' + key;  
    var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex');  
    return sign.toUpperCase();  
}

exports.usualSign = function(ret){

    var string = raw(ret); 
    var key = config.key 
    string = string + '&key=' + key; 
    var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex');  
    return sign.toUpperCase();  
}

exports.raw = function (args) { 
    var keys = Object.keys(args); 
    keys = keys.sort() 
    var newArgs = {}; 
    keys.forEach(function(key) { 
      newArgs[key] = args[key]; 
    }); 
    var string = ''; 
    for (var k in newArgs) { 
      string += '&' + k + '=' + newArgs[k]; 
    } 
    string = string.substr(1); 
    return string; 
  }


